package messageMeServer.model;

import java.util.ArrayList;
import java.util.List;

import messageMeServer.utility.UserDataReader;
import messageMeServer.utility.UserDataWriter;
import messageMeUtility.interfaces.IUser;

public class UserDataBase {

	private static List<DatabaseEntry> users = null;

	private UserDataBase() {

	}

	public static synchronized void initialize() {
		UserDataBase.users = new ArrayList<DatabaseEntry>();
		UserDataBase.loadUsersFromFile();
	}

	public static synchronized void addUser(IUser user) {
		UserDataBase.users.add(new DatabaseEntry(user.getUsername(), user));
		UserDataBase.saveUsersToFile();
	}

	public static synchronized void removeUser(IUser user) {
		UserDataBase.users.remove(user.getUsername());
	}

	public static synchronized int userCount() {
		return UserDataBase.users.size();
	}

	public static synchronized IUser getUser(int index) {
		return UserDataBase.users.get(index).getValue();
	}

	public static synchronized IUser getUser(IUser user) {
		for (DatabaseEntry entry : UserDataBase.users) {
			if (entry.getKey().equals(user.getUsername())) {
				return entry.getValue();
			}
		}
		return null;
	}

	public static synchronized boolean userExists(IUser user) {
		for (DatabaseEntry entry : UserDataBase.users) {
			if (entry.getKey().equals(user.getUsername())) {
				return true;
			}
		}

		return false;
	}

	public static synchronized boolean isUserPasswordCorrect(IUser user) {
		IUser currentUser = UserDataBase.getUser(user);

		if (currentUser.getPassword().equals(user.getPassword()))
			return true;

		return false;
	}

	private static synchronized void loadUsersFromFile() {
		UserDataBase.users.clear();
		UserDataReader reader = new UserDataReader();

		for (IUser user : reader.read()) {
			UserDataBase.addUser(user);
		}
	}

	private static synchronized void saveUsersToFile() {
		UserDataWriter writer = new UserDataWriter();
		List<IUser> tempUsers = new ArrayList<IUser>();

		for (DatabaseEntry entry : UserDataBase.users) {
			tempUsers.add(entry.getValue());
		}
		writer.write(tempUsers);
	}
}
